<template>
  <transition>
    <div v-if="visible" class="detail-main">
      <el-page-header @back="handleClose" :icon="null" class="detail-header">
        <template #title>
          <div class="detail-header-title">
            {{props.id ? '编辑' : '新增'}}
          </div>
        </template>
        <template #content>
          账户信息
        </template>
        <template #extra>
          <div style="flex: auto">
            <el-button type="primary" @click="handleOk(formRef)" :loading="state.subLoading" :icon="Select">
              保存
            </el-button>
            <el-button @click="handleClose" :icon="Back">返回列表</el-button>
          </div>
        </template>
      </el-page-header>
      <div class="detail-form">
        <el-form ref="formRef" :model="formState" :rules="rules" v-loading="state.subLoading" label-width="auto">
          <el-row :gutter="20">
           <el-col :span="20" :offset="1">
              <el-form-item prop="userName" label="用户名">
                <el-input id="userName" v-model="formState.userName" class="w-500" placeholder="请输入用户名" clearable/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="20" :offset="1">
              <el-form-item prop="account" label="账号">
                <el-input id="account" v-model="formState.account" class="w-500" placeholder="请输入账号" clearable/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="20" :offset="1">
              <el-form-item prop="gender" label="性别">
                <el-radio-group v-model="formState.gender" size="small">
                  <el-radio-button label="男" :value="1" />
                  <el-radio-button label="女" :value="2" />
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
           <el-col :span="20" :offset="1">
              <el-form-item v-if="!formState.id" prop="password" label="密码">
                <el-input id="password" type="password" v-model="formState.password" class="w-500" placeholder="请输入密码" show-password clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
           <el-col :span="20" :offset="1">
              <el-form-item prop="roleIds" label="角色">
                <el-select v-model="formState.roleIds" multiple class="w-500">
                  <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
           <el-col :span="20" :offset="1">
              <el-form-item prop="email" label="邮箱">
                <el-input id="email" v-model="formState.email" class="w-500" placeholder="请输入邮箱" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
           <el-col :span="20" :offset="1">
              <el-form-item prop="mobile" label="联系方式">
                <el-input id="mobile" v-model="formState.mobile" class="w-500" placeholder="请输入联系方式" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
           <el-col :span="20" :offset="1">
              <el-form-item prop="deptId" label="所属部门">
                <el-tree-select v-model="formState.deptId" :data="deptTree" :props="treeProps" check-strictly
                                :render-after-expand="false" class="w-500"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
  </transition>
</template>

<script setup name="UserDetail">
import { UserApi } from '@/api/system/user'
import useCurrentInstance from '@/hooks/useCurrentInstance'
import { detailState, rules, setSubLoading, state } from '@/views/system/user/index'
import { CommonApi } from '@/api/common'
import { CacheUtil } from '@/utils/cacheUtil'
import { JSEncrypt } from 'jsencrypt'
import { Select, Back } from '@element-plus/icons-vue'
import {RoleApi} from "@/api/system/role/index.js";
import {DeptApi} from "@/api/system/dept/index.js";

const { proxy } = useCurrentInstance()
const emits = defineEmits(['refreshData'])
let formState = toRef(detailState)
const formRef = ref()
const visible = ref(false)
const roleList = ref([])
const deptTree = ref([])
const treeProps = {
  children: 'children',
  label: 'name',
  value: 'id'
}
const props = defineProps({
  id: {
    type: String,
    required: false
  },
  drawer: {
    type: Boolean,
    required: true
  }
})
//查询角色
function getRoleList() {
  RoleApi.findRoleList({}).then(res => {
    if (res.success) {
      roleList.value = res.data;
    }
  })
}
//查询部门树
function getDepartmentTree() {
  DeptApi.findDepartmentTree().then(res => {
    if (res.success) {
      deptTree.value = res.data;
    }
  })
}

//初始化数据
function initInfo(id) {
  getRoleList();
  getDepartmentTree();
  if (id) {
    setSubLoading(true)
    UserApi.findById({ id }).then((res) => {
      if (res.success) {
        formState.value = res.data
      }
    }).catch((e) => {
      console.log(e);
    }).finally(() => {
      setSubLoading(false)
    })
  }
}

//form表单保存
function handleOk(formEl) {
  if (!formEl) return
  formEl.validate(async (valid, fields) => {
    if (valid) {
      setSubLoading(true)
      if (formState.value.password) {
        const result = await CommonApi.getPublicKey()
        if (result) {
          const { publicKey, sessionGenerateId } = result
          CacheUtil.setSessionGenerateId(sessionGenerateId)
          const encryptor = new JSEncrypt()
          encryptor.setPublicKey(publicKey)
          formState.value.sessionGenerateId = sessionGenerateId;
          formState.value.password = encryptor.encrypt(formState.value.password)
        }
      }
      if (formState.value.id) {
        formState.value.password = null
        UserApi.update(formState.value).then(res => {
          if (res.success) {
            proxy.$message.success(res.message)
            handleClose()
          } else {
            proxy.$message.error(res.message)
          }
        })
      } else {
        UserApi.save(formState.value).then(res => {
          if (res.success) {
            proxy.$message.success(res.message)
            handleClose()
          } else {
            proxy.$message.error(res.message)
          }
        })
      }
      setSubLoading(false)
    } else {
      console.log('error submit!', fields)
    }
  })
}

//关闭弹窗
function handleClose() {
  formRef.value?.resetFields()
  emits('refreshData')
  resetData()
}

//重置数据
function resetData() {
  formState.value = detailState
}

//监听props.visible 值得变化
watch(() => props.drawer, v => {
  visible.value = v
}, { immediate: true, deep: true })

defineExpose({
  initInfo
})

</script>

<style scoped>
</style>
